package com.ddstation.crm.organization_structure.service;


import com.ddstation.crm.institution.entity.DtHealthManageInstitutionEntity;
import com.ddstation.crm.institution.mapper.DtHealthManageInstitutionMapper;
import com.ddstation.crm.organization_structure.util.ExcelUtil;
import com.ddstation.doctor.entity.DdDoctorEntity;
import com.ddstation.doctor.mapper.DdDoctorMapper;
import com.ddstation.exam.entity.DtInvsAutonomyExaminationDataEntity;
import com.ddstation.exam.mapper.DtInvsAutonomyExaminationDataMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@Service @Lazy
public class DataImportServiceImpl implements DataImportService {

    @Override
    public int downloadTemplate(HttpServletResponse response, HttpServletRequest request, String templateType) {
        String fileName = "导入模板";
        String[] columnNames = {};
        List<List<Object>> arrayList = new ArrayList<>();
        switch (templateType){
            case "01":
                fileName += "-医疗机构信息.xlsx";
                columnNames = new String[]{"机构ID", "机构名称", "机构……"};
                for(int i=1;i<3;i++){
                    List<Object> objects = new ArrayList<>();
                    objects.add(10000000+i);
                    objects.add("机构名称"+i);
                    objects.add("机构"+i);
                    arrayList.add(objects);
                }
                break;
            case "02":
                fileName += "-医护信息.xlsx";
                columnNames = new String[]{"医生ID", "医生名称", "医生……"};
                for(int i=1;i<3;i++){
                    List<Object> objects = new ArrayList<>();
                    objects.add(100000+i);
                    objects.add("医生名称"+i);
                    objects.add("医生"+i);
                    arrayList.add(objects);
                }
                break;
            case "03":
                fileName += "-自查自律.xlsx";
                columnNames = new String[]{"医疗机构名称", "类型\n(全面自查/日常自查/专项自查)", "自查日期(字符串格式)", "自查标题", "自查内容", "自查人"};
                for(int i=1;i<3;i++){
                    List<Object> objects = new ArrayList<>();
                    objects.add("示例机构"+i);
                    objects.add(i==1?"全面自查":"日常自查");
                    objects.add("2020-11-11");
                    objects.add("示例标题"+i);
                    objects.add("示例内容"+i);
                    objects.add("示例名称"+i);
                    arrayList.add(objects);
                }
                break;
            default:
                return 0;
        }
        try {
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename="
                    + URLEncoder.encode(fileName, "UTF-8")); // 采用UTF-8编码

            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream outputStream = new BufferedOutputStream(
                    response.getOutputStream());
            ExcelUtil.exportExcel("导入模板", columnNames, arrayList, outputStream,
                    ".xlsx");
            return 1;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return -1;
    }

    Pattern pat = Pattern.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))");

    @Override
    public Map<String, Object> importExcel(String templateType, MultipartFile file, String id) {
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("errorcode", -1);
        String[] columnNames;
        List<String> fields = new ArrayList<>();
        Object obj;
        switch (templateType){
            case "01"://医疗机构信息
                columnNames = new String[]{"id", "name", "address"};
                obj = new DtHealthManageInstitutionEntity();
                break;
            case "02"://医护信息
                columnNames = new String[]{"id", "name", "institutionId"};
                obj = new DdDoctorEntity();
                break;
            case "03"://自查自律
                columnNames = new String[]{"institutionName", "type", "examinationTm", "examinationTitle", "examinationContent", "examinationUser"};
                obj = new DtInvsAutonomyExaminationDataEntity();
                break;
            default:
                retMap.put("errMsg", "类型模板不存在");
                return retMap;
        }
        for(String columnName:columnNames){
            fields.add(columnName);
        }
        int count = 0;
        try{
            List<Object> objects = ExcelUtil.importBaseExcel(file, 0, obj, fields);
            if(objects == null){
                retMap.put("errMsg", "数据转换异常");
                return retMap;
            }
            switch (templateType){
                case "01"://医疗机构信息
                    for(Object object:objects){
                        dtHealthManageInstitutionMapper.insertSelective((DtHealthManageInstitutionEntity) object);
                        count ++;
                    }
                    break;
                case "02"://医护信息
                    for(Object object:objects){
                        ddDoctorMapper.insertSelective((DdDoctorEntity)object);
                        count ++;
                    }
                    break;
                case "03"://自查自律
                    StringBuffer sb = new StringBuffer();
                    List<DtInvsAutonomyExaminationDataEntity> saveList = new ArrayList<>();
                    //定义初始行数
                    int line = 1;
                    //校验参数
                    for(Object object:objects){
                        line++;
                        DtInvsAutonomyExaminationDataEntity entity = (DtInvsAutonomyExaminationDataEntity) object;
                        //医疗机构名称、类型和自查日期必须填写
                        if(StringUtils.isBlank(entity.getInstitutionName()) || StringUtils.isBlank(entity.getType())
                                || StringUtils.isBlank(entity.getExaminationTm())){
                            sb.append(line+"行：医疗机构名称、类型和自查日期必须填写<br>");
                            continue;
                        }
                        //类型必须为：全面自查、日常自查 或 专项自查
                        switch (entity.getType()){
                            case "全面自查":
                                entity.setType("0");
                                break;
                            case "日常自查":
                                entity.setType("1");
                                break;
                            case "专项自查":
                                entity.setType("2");
                                break;
                            default:
                                sb.append(line+"行：类型必须为：全面自查、日常自查或专项自查<br>");
                                continue;
                        }
                        //日期格式
                        if(!pat.matcher(entity.getExaminationTm()).matches()){
                            sb.append(line+"行：日期格式不正确。格式应为YYYY-MM-DD字符串且存在日期<br>");
                            continue;
                        }
                        //医疗机构名称必须存在
                        DtHealthManageInstitutionEntity institutionEntity = dtHealthManageInstitutionMapper.selectByNameAndInstitution(entity.getInstitutionName(), id);
                        if(institutionEntity == null){
                            sb.append(line+"行：医疗机构名称必须存在<br>");
                            continue;
                        }
                        //保存机构ID
                        entity.setInstitutionId(institutionEntity.getId());
                        saveList.add(entity);
                    }
                    if(sb.length() > 0){
                        //存在错误信息则返回提示
                        retMap.put("errMsg", sb.toString());
                        return retMap;
                    }else{
                        //无异常则遍历添加数据
                        for(DtInvsAutonomyExaminationDataEntity entity:saveList) {
                            dtInvsAutonomyExaminationDataMapper.insertSelective(entity);
                            count ++;
                        }
                    }
                    break;
                default:
                    retMap.put("errMsg", "类型模板不存在");
                    return retMap;
            }
        }catch (Exception e){
            e.printStackTrace();
            retMap.put("errMsg", "数据转换异常");
            return retMap;

        }
        retMap.put("errorcode", 1);
        retMap.put("importCount", count);
        return retMap;
    }

    @Inject private DtHealthManageInstitutionMapper dtHealthManageInstitutionMapper = null;
    @Inject private DdDoctorMapper ddDoctorMapper = null;
    @Inject private DtInvsAutonomyExaminationDataMapper dtInvsAutonomyExaminationDataMapper = null;
}
